package org.wangzs.blog.aspect;

import java.lang.reflect.Method;
import java.util.List;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

/**
 * AOP切面类
 * @author wangzs
 *
 */
public class DataSourceAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {
	
	private List<String> prefix;
	
	private String masterDataSource;
	
	public String getMasterDataSource() {
		return masterDataSource;
	}

	public void setMasterDataSource(String masterDataSource) {
		this.masterDataSource = masterDataSource;
	}

	public List<String> getPrefix() {
		return prefix;
	}

	public void setPrefix(List<String> prefix) {
		this.prefix = prefix;
	}

	// service方法执行之前被调用
	public void before(Method method, Object[] args, Object target) throws Throwable {
		String methodName = method.getName();
		boolean master = false;
		for(int i=0;null != prefix && i<prefix.size();i++) {
			if(methodName.startsWith(prefix.get(i))){
				master = true;
				break;
			}
		}
		if(master) {
			System.out.println("切换到: master");
			//DataSourceSwitcher.setMaster();
			DynamicDataSource.setDataSource(masterDataSource);
		} else{
			System.out.println("切换到: slave");
			//DataSourceSwitcher.setSlave();
			DynamicDataSource.setDataSource(null);
		}
	}

	// service方法执行完之后被调用
	public void afterReturning(Object arg0, Method method, Object[] args, Object target) throws Throwable {
	}

	// 抛出Exception之后被调用
	public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {
		//DataSourceSwitcher.setSlave();
		//System.out.println("出现异常,切换到: slave");
	}

}


